<template>
  <div>
    <a-cascader 
      v-model:value="modelValue" 
      :options="useState.options" 
      :placeholder="placeholder" 
      :load-data="useLoadData"
      :fieldNames="{ label, value }"
      change-on-select
      @dropdownVisibleChange="useDropdownVisibleChange"
      />
  </div>
</template>
<script setup>
import { computed, watch } from "vue"
import { useIndex } from "./use-index"
const props = defineProps({
  placeholder: {
    type: String,
    default: "请选择"
  },
  name: {
    type: String,
    default: 'label'
  },
  id: {
    type: String,
    default: 'value'
  },
  children: {
    type: String,
    default: 'children'
  },
  defaultValue: {
    type: Array,
    default: () => ([])
  },
  acitveTop: {
    type: Boolean,
    default: true
  }
})
// hook
const { useState, useDropdownVisibleChange, useLoadData } = useIndex(props)
// label and value，key
const label = computed(() => props.config?.label || props.name )
const value = computed(() => props.config?.value || props.id )
const children = computed(() => props.config?.value || props.id )


const modelValue = defineModel()

/**
 * 默认数据设置叶节点
 */
const initLeafData = (data) => {
  getItem(data)
  /**
   * 获取item
   */
  function getItem(list){
    list.forEach(item => {
      if(item.children) {
        item.isLeaf = false
        getItem(item.children)
      }else{
        item.isLeaf = true
      }
    })
  }
}



watch(() => props.defaultValue, (val) => {
  val.length && initLeafData(val)
  useState.options = val
}, {
  immediate: true // 初始化处理一次
})


</script>